package com.bw.trade.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.core.creditStatus.RefundBorrowStatus;
import com.bw.core.exception.BaseException;
import com.bw.core.utils.HttpClientUtils;
import com.bw.core.utils.MD5Sign;
import com.bw.trade.pojo.TbRefoundLog;
import com.bw.trade.mapper.TbRefoundLogMapper;
import com.bw.trade.service.TbRefoundLogService;
import com.bw.trade.vo.FanHuiVo;
import com.bw.trade.vo.PaymentVo;
import org.omg.CORBA.Environment;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 还款记录表 服务实现类
 * </p>
 *
 * @author lv
 * @since 2021-03-23
 */
@Service
public class TbRefoundLogServiceImpl extends ServiceImpl<TbRefoundLogMapper, TbRefoundLog> implements TbRefoundLogService {

    @Autowired
    private TbRefoundLogMapper refoundLogMapper;
    @Autowired
    private Snowflake snowflake;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private Environment env;

    public void callMethod(TbRefoundLog tbRefoundLog, PaymentVo paymentVo) {


        HashMap<String, String> map = new HashMap<>();

        String merId = "1001";
        String appSercret = "aea43111aa87807fb79939b28256b929";
        //将调用易宝放款平台所需要的参数放入map集合
        map.put("merId", merId);
        map.put("sign", appSercret);
        map.put("name", tbRefoundLog.getUserName());
        map.put("cardId", paymentVo.getCardId());
        map.put("accNo", tbRefoundLog.getRefoundAccount());
        map.put("bankName", tbRefoundLog.getRefoundBankName());
        map.put("bankShortName", tbRefoundLog.getRefoundBankShortName());
        map.put("merTradeNo", tbRefoundLog.getOrderNo());
        map.put("amount", tbRefoundLog.getPayAmount().toString());
        map.put("smsCode", paymentVo.getCode());

        String s = HttpClientUtils.httpPost("http://localhost:8080/api/common/collectionConfirm", map);
        if (StrUtil.hasBlank(s)) {
            throw new BaseException("调用第三方接口失败");
        }
        JSONObject jsonObject = JSON.parseObject(s);
        JSONObject data = jsonObject.getJSONObject("data");
        if(jsonObject.getInteger("code").intValue()!=0){
            throw new BaseException("失败");
        }
        String thirdTradeNo = data.getString("thirdTradeNo");//返回的三方交易单号
        String message = jsonObject.getString("message");
        String resCode = data.getString("resCode");


        TbRefoundLog refoundLog = new TbRefoundLog();
        refoundLog.setId(tbRefoundLog.getId());//根据主键进行修改
        refoundLog.setTransactionNo(thirdTradeNo);
        refoundLog.setReturnCode(resCode);
        refoundLog.setReturnMsg(message);

        refoundLogMapper.updateById(refoundLog);

    }

    //根据交易单号查询结果(定时任务查询)
    // @Scheduled(fixedRate = 5000)
    public List<TbRefoundLog> repayment () {
        System.out.println("定时器开启");


        //查询所有状态为处理中的记录
        QueryWrapper<TbRefoundLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("refound_status", RefundBorrowStatus.REFUND_BORROW_CHECK_RUNNING);
        List<TbRefoundLog> list = refoundLogMapper.selectList(queryWrapper);
        list.forEach(a->{
            HashMap<String, Object> map = new HashMap<>();
            map.put("merId", snowflake.nextIdStr() + "");
            map.put("sign", MD5Sign.md5Encode( "abc..."));
            map.put("thirdTradeNo",a.getOutTradeNo());
            String str = HttpUtil.post("http://localhost:8080/api/common/queryTradeResult", map);

            JSONObject jsonObject = JSON.parseObject(str);
            JSONObject data = jsonObject.getJSONObject("data");
            if(jsonObject.getInteger("code").intValue()!=0){
                return;
            }
            String msgInfo = data.getString("msgInfo");
            String thirdTradeNo = data.getString("thirdTradeNo");
            String resCode = data.getString("resCode");//返回Code
            if(resCode!="1001"){
                return;
            }
            QueryWrapper<TbRefoundLog> wrapper = new QueryWrapper<>();
            wrapper.eq("out_trade_no",a.getOutTradeNo());
            TbRefoundLog tbRefoundLog = refoundLogMapper.selectOne(queryWrapper);

            FanHuiVo fanHuiVo1 = new FanHuiVo();
            fanHuiVo1.setOrderNo(tbRefoundLog.getOrderNo());
            fanHuiVo1.setStartDate(new Date());

            String s1 = JSON.toJSONString(fanHuiVo1);
            amqpTemplate.convertAndSend("item_plan",s1);//推送信息给业务

            TbRefoundLog tbRefoundLog1 = new TbRefoundLog();
            tbRefoundLog1.setId(tbRefoundLog.getId());
            tbRefoundLog1.setRefoundStatus(RefundBorrowStatus.REFUND_BORROW_SUCCESS);
            refoundLogMapper.updateById(tbRefoundLog1);
        });


        return list;

    }
}
